class Conference < ActiveRecord::Base
  STATUSES = {
      opened: ActionController::Base.helpers.t('conferences.status.opened'),
      closed: ActionController::Base.helpers.t('conferences.status.closed'),
      not_opened: ActionController::Base.helpers.t('conferences.status.not_opened')
  }
  MEMBERS_PAGE_COUNT = 10
  paginates_per 10

  has_one :document, :as => :source, :dependent => :destroy
  has_and_belongs_to_many :members, :class_name => 'User', :order => :first_name
  has_many :reports, :dependent => :destroy

  default_scope order('created_at DESC')

  after_initialize lambda { |c| c.build_document }, :unless => :document

  accepts_nested_attributes_for :document

  validates_with ConferenceValidator

  validates_presence_of :document, :start_date, :end_date

  def status
    if opened?
      :opened
    elsif not_opened?
      :not_opened
    elsif closed?
      :closed
    end
  end

  def opened?
    now = DateTime.now
    now > self.start_date && now < self.end_date
  end

  def closed?
    DateTime.now > self.end_date
  end

  def not_opened?
    DateTime.now < self.start_date
  end

  def get_paginated_members(page=1, remaining=false)
    page = Integer(page) rescue return

    if page > 0
      offset = page * MEMBERS_PAGE_COUNT - MEMBERS_PAGE_COUNT
      unless remaining
        self.members.offset(offset).limit(MEMBERS_PAGE_COUNT)
      else
        self.members.offset(offset).all
      end
    end
  end

  def members_to_json(members)
    if members.present?
      members.map do |member|
        {
          full_name: member.full_name,
          avatar: member.avatar_url,
          reports: self.reports.search('document_user_id_eq' => member.id).count
        }
      end
    end
  end
end
